package com.github.gin.sns.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by GinPonson on 1/2/2017.
 */
public class MeiDoTalk {

    public static String talk(String word){
        HttpPost post = new HttpPost("http://m.mengbaotao.com/api.php?cmd=chatCallback");

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("msg", word));
        params.add(new BasicNameValuePair("openid", "866361022977440"));
        params.add(new BasicNameValuePair("channelid", "2001"));

        post.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));

        post.setHeader("Host", "m.mengbaotao.com");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("Connection", "Keep-Alive");
        post.setHeader("User-Agent", "okhttp/2.7.0");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        String message = "";
        try {

            HttpClientBuilder builder =  HttpClientBuilder.create()
                    .addInterceptorFirst((HttpResponse response,HttpContext context) -> {
                        HttpEntity entity = response.getEntity();
                        Header contentEncoding = entity.getContentEncoding();
                        if(contentEncoding != null){
                            for(HeaderElement element : contentEncoding.getElements()){
                                if (element.getName().equalsIgnoreCase("gzip")) {
                                    response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                    return;
                                }
                            }
                        }
                    });
            HttpClient client = builder.build();

            HttpResponse response = client.execute(post);
            HttpEntity resEntity = response.getEntity();
            message = IOUtils.toString(resEntity.getContent(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(talk("小鸡鸡"));
    }
}
